
function initComposer () {
	gData.composer = {};
	gData.composer.numAttachments = 0;

	var resource = getResource();
	if (resource) {
		var opList = resource.split('.');
		callJSON ('/ui/content/mail/' + opList[1],
			  fillMailData, opList);
	}
}

function addAttachment () {
	var text = '<input type="file" size="60" name="attach.' +
		gData.composer.numAttachments + '">';
	var tableText = '<tr><td>Attach:</td><td>' + text + '</td></tr>';
	$('attachments').innerHTML += tableText;
	gData.composer.numAttachemnts++;
}


function filterAddr(addr) {
	var output = '';
	for (var i = 0; i < addr.length; i++) {
		ch = addr.charAt(i);
		if (ch != '\r' && ch != '\n' && ch != '\t')
			output += ch;
		else output += ' ';		
	}
	return output;
}

function fillMailData (servReturn, opList) {
	var data = servReturn[0];
	var op = opList[0];
	var docID = opList[1];
	var form = document.forms[0];

	$('composerTitle').innerHTML = 'Reply to: ' + data.subject.escapeHTML();
		
	if (op == 'reply') {
		form.subject.value = replySubject(data.subject);
		form.to.value = data.from;
		form.replyto.value = data.messageid;

		$('checkIsRefAttach').style.display = 'block';
		form.refattach.value = '' + docID;
	} else if (op == 'replyall') {
		form.subject.value = replySubject(data.subject);
		form.to.value = filterAddr(data.from) + ', ' + filterAddr(data.to);
		form.cc.value = filterAddr(data.cc);
		$('checkIsRefAttach').style.display = 'block';
		form.refattach.value = '' + docID;
	} else if (op == 'forward') {
		form.subject.value = 'Fwd: ' + data.subject;
		form.cc.value = filterAddr(data.from);

		$('checkIsRefAttach').style.display = 'block';
		form.refattach.value = '' + docID;
		form.isrefattach.checked = true;
	}

	if (op == 'reply' || op == 'replyall') {
		form.content.value = '\r\n\r\n' +
			quoteContent (data.content);
	} else if (op == 'forward') {
		form.content.value = '\r\n\r\n' +
			'------ Forwarded Messages ------\r\n\r\n' +
			data.content;		
	}
}

function replySubject (subject) {
	var test = subject.substring(0, 3).toUpperCase();
	if (test == 'RE:')
		return subject;
	else
		return 'Re: ' + subject;	
}

function quoteContent (content) {
	var lines = content.split('\r\n');
	var output = '------ Original Message ------\r\n>\r\n';
	for (var i in lines) {
		output += ('> ' + lines[i] + '\r\n');
	}
	return output;
}
